# 导入所需的库
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, classification_report
from sklearn import tree
import matplotlib.pyplot as plt

# 加载 Iris 数据集
# iris = load_iris()
# X, y = iris.data, iris.target
X,y = load_iris(return_X_y=True)

# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# 创建决策树分类器
clf = DecisionTreeClassifier(random_state=42)

# 训练模型
clf.fit(X_train, y_train)

# 预测测试集
y_pred = clf.predict(X_test)

# 评估模型
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2f}")

# print("Classification Report:")
# print(classification_report(y_test, y_pred))

# # 可视化决策树
# plt.figure(figsize=(20,10))
# tree.plot_tree(clf, filled=True, feature_names=iris.feature_names, class_names=iris.target_names)
# plt.show()
